import Vue from 'vue'
import storage from 'store'
import { login, logout, phoneLogin, thirdLogin } from '@/api/login'
import {
  ACCESS_TOKEN,
  USER_NAME,
  USER_INFO,
  USER_AUTH,
  SYS_BUTTON_AUTH,
  UI_CACHE_DB_DICT_DATA,
  TENANT_ID,
  DEPARTID,
  REGIONCD,
  ROLEID,
  CACHE_INCLUDED_ROUTES,
  POSITION_INFO
} from '@/store/mutation-types'
// import { welcome, objToStrMap, strMapToObj } from '@/utils/util'
import { queryPermissionsByRoleId } from '@/api/api'
import { getAction } from '@/api/manage'

const user = {
  state: {
    token: '',
    username: '',
    realname: '',
    tenantid: '',
    welcome: '',
    avatar: '',
    permissionList: [],
    info: {},
    positionInfo: {},
    departId: '',
    regionCd: '',
    roleId: '',
    // 系统安全模式
    sysSafeMode: null,
    // // ======================== 好视通 start =========================
    // localUser: {},
    // localPubAudio: false, // 本地广播音频状态
    // audioStatus: 4, // 本地麦克风状态 1 正在语音 2 关闭语音状态  3 关闭语音 无权限需举手状态  4 举手待放下手状态 5 无麦克风
    // localPubVideo: false, // 本地广播视频状态
    // videoStatus: 4, // 本地摄像头状态 1 已打开视频 2 关闭视频状态  3 关闭视频 无权限需举手状态 4 举手待放下手状态 5 无摄像头
    // groupUserList: {}, // 用户群组
    // userListShow: false, // 用户列表显示状态
    // inviteShow: false // 邀请参会人弹框
    // // ======================== 好视通 over  =========================
  },

  mutations: {
    SET_TOKEN: (state, token) => {
      Vue.ls.set('token', token, {
        domain: '.weique360.com'
      })
      state.token = token
    },
    SET_NAME: (state, { username, realname, welcome }) => {
      state.username = username
      state.realname = realname
      state.welcome = welcome
    },
    SET_AVATAR: (state, avatar) => {
      state.avatar = avatar
    },
    SET_PERMISSIONLIST: (state, permissionList) => {
      state.permissionList = permissionList
    },
    SET_INFO: (state, info) => {
      state.info = info
    },
    SET_POSITIONINFO: (state, positionInfo) => {
      state.positionInfo = positionInfo
    },
    SET_TENANT: (state, id) => {
      state.tenantid = id
    },
    SET_SYS_SAFE_MODE: (state, sysSafeMode) => {
      if (typeof sysSafeMode === 'boolean') {
        state.sysSafeMode = sysSafeMode
      } else {
        state.sysSafeMode = false
      }
    },
    SET_DEPARTID: (state, id) => {
      state.departId = id
    },
    SET_REGIONCD: (state, id) => {
      state.regionCd = id
    },
    SET_ROLEID: (state, id) => {
      state.roleId = id
    },
    // ======================== 好视通 start =========================
    SET_INVITE_SHOW: (state, bool) => {
      state.inviteShow = bool
    },
    SET_USER_LIST_SHOW: (state, bool) => {
      state.userListShow = bool
    },
    SET_LOCALUSER: (state, info) => {
      state.localUser = { ...state.localUser, ...info }
    },
    TOOGEL_LOCALPUBAUDIO: (state, bool) => {
      state.localPubAudio = bool
    },
    TOOGLE_LOCALPUBVIDEO: (state, bool) => {
      state.localPubVideo = bool
    },
    SET_AUDIOSTATUS: (state, sta) => {
      state.audioStatus = sta
    },
    SET_VIDEOSTATUS: (state, sta) => {
      state.videoStatus = sta
    },
    SET_GROUPINFO: (state, info) => {
      state.groupUserList = info
    },
    // UPDATE_GROUPINFO: (state, data) => {
    //   // console.log('udate groupuser-----------------------------')
    //   const groupUserMap = objToStrMap(state.groupUserList)
    //   const user = Object.assign({}, groupUserMap.get(data.UserID), data)
    //   groupUserMap.set(data.UserID, user)
    //   state.groupUserList = strMapToObj(groupUserMap)
    // },
    // DELETE_GROUPINFO: (state, key) => {
    //   const groupUserMap = objToStrMap(state.groupUserList)
    //   groupUserMap.delete(key + '')
    //   state.groupUserList = strMapToObj(groupUserMap)
    // },
    CLEAR_GROUPINFO: (state) => {
      // 清空用户
      state.groupUserList = {}
    },
    CLEAR_LOCAL_USER: (state) => {
      state.localUser = {}
    }
    // ======================== 好视通 over  =========================
  },

  actions: {
    // CAS验证登录
    ValidateLogin({ commit }, userInfo) {
      return new Promise((resolve, reject) => {
        getAction('/sys/cas/client/validateLogin', userInfo)
          .then((response) => {
            console.log('----cas 登录--------', response)
            if (response.success) {
              const result = response.result
              const userInfo = result.userInfo
              Vue.ls.set(ACCESS_TOKEN, result.token, 7 * 24 * 60 * 60 * 1000)
              Vue.ls.set(USER_NAME, userInfo.username, 7 * 24 * 60 * 60 * 1000)
              Vue.ls.set(USER_INFO, userInfo, 7 * 24 * 60 * 60 * 1000)
              commit('SET_TOKEN', result.token)
              commit('SET_INFO', userInfo)
              // commit('SET_NAME', { username: userInfo.username, realname: userInfo.realname, welcome: welcome() })
              commit('SET_AVATAR', userInfo.avatar)
              resolve(response)
            } else {
              resolve(response)
            }
          })
          .catch((error) => {
            reject(error)
          })
      })
    },
    // 登录
    Login({ commit }, userInfo) {
      userInfo = {
        username: 'admin',
        password: '&XYyszzA004',
        checkKey: new Date().getTime(),
        originApp: 'App'
      }
      return new Promise((resolve, reject) => {
        login(userInfo)
          .then((response) => {
            if (response.code == '200') {
              const result = response.result
              const userInfo = result.userInfo
              Vue.ls.set(ACCESS_TOKEN, result.token, 7 * 24 * 60 * 60 * 1000)
              Vue.ls.set(USER_NAME, userInfo.username, 7 * 24 * 60 * 60 * 1000)
              Vue.ls.set(USER_INFO, userInfo, 7 * 24 * 60 * 60 * 1000)
              Vue.ls.set(UI_CACHE_DB_DICT_DATA, result.sysAllDictItems, 7 * 24 * 60 * 60 * 1000)
              commit('SET_TOKEN', result.token)
              commit('SET_INFO', userInfo)
              // commit('SET_NAME', { username: userInfo.username, realname: userInfo.realname, welcome: welcome() })
              commit('SET_AVATAR', userInfo.avatar)
              resolve(response)
            } else {
              reject(response)
            }
          })
          .catch((error) => {
            reject(error)
          })
      })
    },
    //手机号登录
    PhoneLogin({ commit }, userInfo) {
      return new Promise((resolve, reject) => {
        phoneLogin(userInfo)
          .then((response) => {
            if (response.code == '200') {
              const result = response.result
              const userInfo = result.userInfo
              Vue.ls.set(ACCESS_TOKEN, result.token, 7 * 24 * 60 * 60 * 1000)
              Vue.ls.set(USER_NAME, userInfo.username, 7 * 24 * 60 * 60 * 1000)
              Vue.ls.set(USER_INFO, userInfo, 7 * 24 * 60 * 60 * 1000)
              Vue.ls.set(UI_CACHE_DB_DICT_DATA, result.sysAllDictItems, 7 * 24 * 60 * 60 * 1000)
              commit('SET_TOKEN', result.token)
              commit('SET_INFO', userInfo)
              commit('SET_NAME', { username: userInfo.username, realname: userInfo.realname, welcome: welcome() })
              commit('SET_AVATAR', userInfo.avatar)
              resolve(response)
            } else {
              reject(response)
            }
          })
          .catch((error) => {
            reject(error)
          })
      })
    },
    // 获取用户信息
    GetPermissionList({ commit }) {
      return new Promise((resolve, reject) => {
        queryPermissionsByRoleId({
          roleId: Vue.ls.get(ROLEID)
        })
          .then((response) => {
            const menuData = response.result.menu
            const authData = response.result.auth
            const allAuthData = response.result.allAuth
            //Vue.ls.set(USER_AUTH,authData);
            sessionStorage.setItem(USER_AUTH, JSON.stringify(authData))
            sessionStorage.setItem(SYS_BUTTON_AUTH, JSON.stringify(allAuthData))
            if (menuData && menuData.length > 0) {
              // //update--begin--autor:qinfeng-----date:20200109------for：JEECG-63 一级菜单的子菜单全部是隐藏路由，则一级菜单不显示------
              // menuData.forEach((item, index) => {
              //   if (item["children"]) {
              //     let hasChildrenMenu = item["children"].filter((i) => {
              //       return !i.hidden || i.hidden == false
              //     })
              //     if (hasChildrenMenu == null || hasChildrenMenu.length == 0) {
              //       item["hidden"] = true
              //     }
              //   }
              // })
              // //console.log(" menu show json ", menuData)
              // //update--end--autor:qinfeng-----date:20200109------for：JEECG-63 一级菜单的子菜单全部是隐藏路由，则一级菜单不显示------
              commit('SET_PERMISSIONLIST', menuData)
              // 设置系统安全模式
              commit('SET_SYS_SAFE_MODE', response.result.sysSafeMode)
            } else {
              reject('getPermissionList: permissions must be a non-null array !')
            }
            resolve(response)
          })
          .catch((error) => {
            reject(error)
          })
      })
    },

    // 登出
    Logout({ commit, state }) {
      return new Promise((resolve) => {
        let logoutToken = state.token
        commit('SET_TOKEN', '')
        commit('SET_PERMISSIONLIST', [])
        Vue.ls.remove(ACCESS_TOKEN)
        Vue.ls.remove(USER_INFO)
        Vue.ls.remove(USER_NAME)
        Vue.ls.remove(UI_CACHE_DB_DICT_DATA)
        Vue.ls.remove(CACHE_INCLUDED_ROUTES)
        Vue.ls.remove(TENANT_ID)
        Vue.ls.remove(DEPARTID)
        Vue.ls.remove(REGIONCD)
        Vue.ls.remove(ROLEID)
        //console.log('logoutToken: '+ logoutToken)
        logout(logoutToken)
          .then(() => {
            if (process.env.VUE_APP_SSO == 'true') {
              let sevice = 'http://' + window.location.host + '/'
              let serviceUrl = encodeURIComponent(sevice)
              window.location.href = process.env.VUE_APP_CAS_BASE_URL + '/logout?service=' + serviceUrl
            }
            resolve()
          })
          .catch(() => {
            resolve()
          })
      })
    },
    // 第三方登录
    ThirdLogin({ commit }, param) {
      return new Promise((resolve, reject) => {
        thirdLogin(param.token, param.thirdType)
          .then((response) => {
            if (response.code == '200') {
              const result = response.result
              const userInfo = result.userInfo
              Vue.ls.set(ACCESS_TOKEN, result.token, 7 * 24 * 60 * 60 * 1000)
              Vue.ls.set(USER_NAME, userInfo.username, 7 * 24 * 60 * 60 * 1000)
              Vue.ls.set(USER_INFO, userInfo, 7 * 24 * 60 * 60 * 1000)
              commit('SET_TOKEN', result.token)
              commit('SET_INFO', userInfo)
              commit('SET_NAME', { username: userInfo.username, realname: userInfo.realname, welcome: welcome() })
              commit('SET_AVATAR', userInfo.avatar)
              resolve(response)
            } else {
              reject(response)
            }
          })
          .catch((error) => {
            reject(error)
          })
      })
    },
    saveTenant({ commit }, id) {
      Vue.ls.set(TENANT_ID, id, 7 * 24 * 60 * 60 * 1000)
      commit('SET_TENANT', id)
    },
    saveLoginDepart({ commit }, departInfo) {
      Vue.ls.set(DEPARTID, departInfo.departId, 7 * 24 * 60 * 60 * 1000)
      Vue.ls.set(REGIONCD, departInfo.regionCd, 7 * 24 * 60 * 60 * 1000)
      Vue.ls.set(ROLEID, departInfo.roleId, 7 * 24 * 60 * 60 * 1000)
      Vue.ls.set(POSITION_INFO, departInfo, 7 * 24 * 60 * 60 * 1000)
      commit('SET_DEPARTID', departInfo.departId)
      commit('SET_REGIONCD', departInfo.regionCd)
      commit('SET_ROLEID', departInfo.roleId)
      commit('SET_POSITIONINFO', departInfo)
    },
    // ======================== 好视通 start =========================
    SetLocalUser({ commit }, info) {
      // 设置本地用户信息
      commit('SET_LOCALUSER', info)
      storage.set('localuser', info)
    },
    SetLocalPubAudio({ commit }, bool) {
      // 设置广播音频状态
      commit('TOOGEL_LOCALPUBAUDIO', bool)
    },
    SetAudioStatus({ commit }, status) {
      // 设置麦克风的状态
      commit('SET_AUDIOSTATUS', status)
    },
    SetLocalPubVideo({ commit }, bool) {
      // 设置广播视频状态
      commit('TOOGLE_LOCALPUBVIDEO', bool)
    },
    SetVideoStatus({ commit }, status) {
      // 设置摄像头的状态
      commit('SET_VIDEOSTATUS', status)
    },
    SetGroupInfo({ commit }, info) {
      // 设置组成员信息
      commit('SET_GROUPINFO', info)
    },
    UpdateGroupInfo({ commit }, data) {
      // 增加or修改用户
      commit('UPDATE_GROUPINFO', data)
    },
    DeleteGroupInfo({ commit }, data) {
      // 删除用户
      commit('DELETE_GROUPINFO', data)
    },
    ClearGroupInfo({ commit }, data) {
      // 清空用户
      commit('DELETE_GROUPINFO', data)
    }
    // ======================== 好视通 over  =========================
  }
}

export default user
